package org.ala.tiktools.rpc.kcp.netty.tools;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;

/**
 * @author ala
 * @date 2025-04-15 10:35
 */
public class NettyTools {
    /**
     *  触发异常并且关闭
     */
    public static void fireExceptionAndClose(Channel channel, Throwable ex) {
        channel.pipeline().fireExceptionCaught(ex);
        if (channel.isActive()) {
            Channel.Unsafe unsafe = channel.unsafe();
            unsafe.close(unsafe.voidPromise());
        }
    }
    /**
     *  触发read
     *  <p> bufList中的数据还是一个一个触发的
     */
    public static void fireChannelRead(Channel ch, CodecOutputList<ByteBuf> bufList) {
        ChannelPipeline pipeline = ch.pipeline();
        int size = bufList.size();
        if (size <= 0) {
            return;
        }
        for (int i = 0; i < size; i++) {
            ByteBuf msg = bufList.getUnSafe(i);
            pipeline.fireChannelRead(msg);
        }
        pipeline.fireChannelReadComplete();
    }
}
